package com.qq.weixin.mp.message.hxexp.service.impl;

import java.io.IOException;
import java.io.StringReader;

import javax.xml.bind.JAXBException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.hxexp.weixin.common.jaxb.JaxbMarshallerHelper;
import com.hxexp.weixin.common.jaxb.JaxbUnmarshallerHelper;
import com.qq.weixin.constant.AutoReplyKeywords;
import com.qq.weixin.constant.MsgType;
import com.qq.weixin.mp.message.hxexp.model.receive.BaseMsgJaxb;
import com.qq.weixin.mp.message.hxexp.model.receive.TextMsgJaxb;
import com.qq.weixin.mp.message.hxexp.model.send.BaseReplyJaxb;
import com.qq.weixin.mp.message.hxexp.model.send.TextReplyJaxb;
import com.qq.weixin.mp.message.hxexp.service.TextMessageService;

/**
 * 文本消息服务实现类
 * @author li.jiang
 *
 */
@Service
public final class TextMessageServiceImpl implements TextMessageService {
    private static final Logger LOGGER = LoggerFactory.getLogger(TextMessageServiceImpl.class);
    @Value("${auto.reply.msg}")
    private String autoReplyMsg;
    @Value("${kf.menu.msg}")
    private String kfMenuMsg;
    @Value("${kf.faq.msg}")
    private String kfFaqMsg;
    /* (non-Javadoc)
     * @see com.hxexp.weixin.pubac.reply.service.TextMessageService#receiveAndReply(java.lang.String)
     */
    @Override
    public String receiveAndReply(String xmlMsg) throws JAXBException, IOException {
        TextMsgJaxb recTxt = (TextMsgJaxb) JaxbUnmarshallerHelper.unmarshal(new StringReader(xmlMsg),
                new Class<?>[] { BaseMsgJaxb.class, TextMsgJaxb.class });
        LOGGER.debug("接收到的消息已转换成对象: {}", recTxt.toString());

        TextReplyJaxb replyMsg = new TextReplyJaxb();
        replyMsg.setToUserName(recTxt.getFromUserName());
        replyMsg.setFromUserName(recTxt.getToUserName());
        replyMsg.setCreateTime(System.currentTimeMillis());
        replyMsg.setMsgType(MsgType.TEXT);

        // 根据用户发送的不同关键字创建回复给用户的消息
        String word = recTxt.getContent().trim().toLowerCase();
        if (AutoReplyKeywords.KFZX.equals(word)) { // 客服中心
            replyMsg.setContent(kfMenuMsg);
        } else if (AutoReplyKeywords.KFZX_FAQ.equals(word)) { // 常见问题
            replyMsg.setContent(kfFaqMsg);
        } else if (AutoReplyKeywords.KFZX_KF.equals(word)) { // 接入人工客服
            BaseReplyJaxb kfJaxb = new BaseReplyJaxb();
            kfJaxb.setToUserName(recTxt.getFromUserName());
            kfJaxb.setFromUserName(recTxt.getToUserName());
            kfJaxb.setCreateTime(System.currentTimeMillis());
            kfJaxb.setMsgType(MsgType.KF); // 回复此消息类别,微信服务器将把用户转接到多客服系统

            return JaxbMarshallerHelper.marshalToString(kfJaxb);
        } else {
            replyMsg.setContent(autoReplyMsg);
        }
        // 将回复内容转换成XML消息
        return JaxbMarshallerHelper.marshalToString(replyMsg);
    }

}
